from google.appengine.ext import ndb

class PC (ndb.Model):
    """Models an individual parent and child entry """

    child_id = ndb.StringProperty()
    parent_id = ndb.StringProperty()
    child_parent_id = ndb.StringProperty()  # child_id + parent_id

    @staticmethod
    def create_parent_child_entity(parent_id_given, child_id_given):
        """ create a new entity for parent and his child """
        unique_id = child_id_given + parent_id_given
        pc = PC(child_id=child_id_given, parent_id=parent_id_given, child_parent_id = unique_id)
        check_pc_exists = PC.query(PC.child_parent_id == unique_id).get()
        if check_pc_exists != None:
            return -1
        else:
            pc.put()
            return 1

    @staticmethod
    def check_existence_parent_child_entity(parent_id_given, child_id_given):
        """ return 1 iff there is an entity with those values"""
        unique_id = child_id_given + parent_id_given
        check_pc_exists = PC.query(PC.child_parent_id == unique_id).get()
        if (check_pc_exists is not None):
            return 1
        return -1
    @staticmethod
    def delete_entities_by_parent_id(parent_id_given):
        """ delete entity by given parent id (email address) """
        entities_to_delete = ndb.gql("SELECT * FROM PC WHERE parent_id IN (:mail)", mail=parent_id_given)
        for ent in entities_to_delete:
            ent.key.delete()

    @staticmethod
    def delete_entities_by_child_id(child_id_given):
        """ delete entity by given child id """
        entities_to_delete = ndb.gql("SELECT * FROM PC WHERE child_id IN (:mail)", mail=child_id_given)
        for ent in entities_to_delete:
            ent.key.delete()


    @staticmethod
    def get_children_by_parent_mail_address(parent_email_address):
        """ Returns list with all ids of children of a parent with email address given """
        childs = ndb.gql("SELECT * FROM PC WHERE parent_id IN (:mail)", mail=parent_email_address)
        child_list = []
        for child in childs:
            child_list.append(child.child_id)
        return child_list

    @staticmethod
    def get_children_by_parent_mail_address(parent_email_address):
        """ Returns list with all ids of children of a parent with email address given """
        childs = ndb.gql("SELECT * FROM PC WHERE parent_id IN (:mail)", mail=parent_email_address)
        child_list = []
        for child in childs:
            child_list.append(child.child_id)
        return child_list

    @staticmethod
    def get_parents_id_by_child_id(child_id_given):
        """ Return list with parents ids of child with given id """
        entities = ndb.gql("SELECT * FROM PC WHERE child_id IN (:child_id)", child_id = child_id_given)
        parents_ids = []
        for ent in entities:
            parents_ids.append(ent.parent_id)
        return parents_ids
